﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TCPClient
{
    public partial class Form1 : Form
    {

        bool status = false;//服务开启状态
        private string linebreak = "\r\n";
        Socket socketClient = null;
        Thread threadClient = null;
        public Form1()
        {
            InitializeComponent();
            GetNativeIp();
            text_port.Text = "8080";


        }
        public void GetNativeIp()
        {
            IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in hostEntry.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    text_ip.Text = ip.ToString();
                }
            }
        }
        public string GetNowTime()
        {
            string time = DateTime.Now.ToString();
            return time;
        }

        private void btn_connect_Click(object sender, EventArgs e)
        {
            if (status == false)
            {
                socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //绑定用户输入的ip和地址
                try
                {
                    socketClient.Connect(new IPEndPoint(IPAddress.Parse(text_ip.Text.Trim()), int.Parse(text_port.Text.Trim())));
                    ChatList.AppendText("连接服务成功---" + GetNowTime() + linebreak);
                    status = true;
                    threadClient = new Thread(ReciveData);
                    threadClient.IsBackground = true;
                    threadClient.Start();
                    btn_connect.Text = "关闭";
                }
                catch(Exception ex)
                {   
                    ChatList.AppendText("错误:---" + ex.Message+linebreak);
                    

                }
              
            }
            else if (status == true)
            {
                btn_connect.Text = "连接";
                ChatList.Text = string.Empty;
                Disconnect();
            }
        }

        private void ReciveData()
        {
            while (true)
            {
                try
                {
                byte[] data = new byte[1024 * 2];
                int length =  socketClient.Receive(data);//将收到的数据存入缓存区并返回收到的字节数
                string recivedata = Encoding.UTF8.GetString(data).Replace("\0", "");
                string str = "服务端：" + GetNowTime() + linebreak + recivedata + linebreak;
                ChatList.Invoke(new Action(() => { ChatList.AppendText(str); }));
                }
                catch (Exception e)
                {     

                    ChatList.Invoke(new Action(() => { ChatList.AppendText("错误:---" + e.Message+linebreak); }));
                    status = false;
                    btn_connect.Invoke(new Action(() => { btn_connect.Text = "连接"; }));
                  
                    return;
                }
               
            }
        }

        public void Disconnect()
        {
            status = false;
            socketClient.Close();
            socketClient = null;
          

        }
        private void btn_send_Click(object sender, EventArgs e)
        {
            if (senddata.Text.Length > 0)
            {

                SendMessage(senddata.Text.Trim());
            }
            else ChatList.AppendText("发送数据不能为空" + linebreak);
        }
        public void SendMessage(string message)
        {
            byte[] data = Encoding.UTF8.GetBytes(message);
            socketClient.Send(data);
            ChatList.AppendText("客户端： " + GetNowTime() + linebreak + message+ linebreak);
        }
    }
}
